package uk.co.richardwkirk.parkrun.android;

import java.util.List;

import uk.co.richardwkirk.parkrun.android.storage.AthleteDataSource;
import uk.co.richardwkirk.parkrun.android.storage.AthleteData;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AthleteChoice extends Activity {

	private class AthleteListAdapter extends ArrayAdapter<AthleteData> {

		List<AthleteData> items;

		public AthleteListAdapter(Context context, int textViewResourceId, List<AthleteData> values) {
			super(context, textViewResourceId, values);
			this.items = values;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.athlete_choice_list_item, null);
			}

			AthleteData athlete = items.get(position);
			if (athlete != null) {
				TextView tt = (TextView) v.findViewById(R.id.athlete_list_item_toptext);
				tt.setText(athlete.getName());
				
				ImageView iv = (ImageView) v.findViewById(R.id.athlete_list_item_icon);
				String club = athlete.getClub();
				if (club != null) {
					if (club.equals("10")) {
						iv.setImageDrawable(getResources().getDrawable(R.drawable.club10));
					}
					else if (club.equals("50")) {
						iv.setImageDrawable(getResources().getDrawable(R.drawable.club50));
					}
					else if (club.equals("100")) {
						iv.setImageDrawable(getResources().getDrawable(R.drawable.club100));
					}
					else if (club.equals("250")) {
						iv.setImageDrawable(getResources().getDrawable(R.drawable.club250));
					}
				}
			}

			return v;
		}

	}

	AthleteListAdapter adapter = null;

	private AthleteDataSource datasource;
	
	// TODO: I would like to remove mode and have the parent handle where we go next
	private long mode = IntentExtras.ATHLETE_CHOICE_MODE_DISPLAY;
	private long type = IntentExtras.ATHLETE_CHOICE_TYPE_SELECTED_ATHLETE;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.athlete_choice);

		// What mode/type are we working with?
		Intent intent = getIntent();
		this.mode = intent.getIntExtra(IntentExtras.EXTRA_ATHLETE_CHOICE_MODE, IntentExtras.ATHLETE_CHOICE_MODE_DISPLAY);
		this.type = intent.getIntExtra(IntentExtras.EXTRA_ATHLETE_CHOICE_TYPE, IntentExtras.ATHLETE_CHOICE_TYPE_SELECTED_ATHLETE);
		
		Log.d("PARKRUN", "Athlete choice mode set to: " + this.mode);
		Log.d("PARKRUN", "Athlete choice type set to: " + this.type);
		
		if (type == IntentExtras.ATHLETE_CHOICE_TYPE_COMPARE_ATHLETE) {
			this.setTitle("Select athlete to compare against...");
		}
		else {
			this.setTitle("Select athlete...");
		}
		
		reloadListValues();
	}

	private void reloadListValues() {
		// Athlete list is held in the SQL db storage
		datasource = new AthleteDataSource(this);
		datasource.open();

		// Load the athlete list
		// TODO: Make the athlete list load into an async task
		List<AthleteData> values = datasource.getAthleteList();

		datasource.close();

		ListView athleteListView = (ListView) findViewById(R.id.athlete_id_list);
		adapter = new AthleteListAdapter(this, android.R.layout.simple_list_item_1, values);
		athleteListView.setAdapter(adapter);
		athleteListView.setOnItemClickListener(new AthleteListClickListener());
		athleteListView.setOnItemLongClickListener(new AthleteListLongClickListener());
	}

	@Override
	protected void onResume() {
		datasource.open();
		super.onResume();
	}

	@Override
	protected void onPause() {
		datasource.close();
		super.onPause();
	}
	

	void handleAthleteChoice(long athleteId) {
		setAthleteSelectionByType(athleteId);
		returnAthleteSelectionByMode(athleteId);
	}

	private void setAthleteSelectionByType(long athleteId) {
		// Set the athlete id on the active selections deending on type
		if (type == IntentExtras.ATHLETE_CHOICE_TYPE_SELECTED_ATHLETE) {
			ActiveSelections.getSingleton().setAthleteId(athleteId);
		}
		else if (type == IntentExtras.ATHLETE_CHOICE_TYPE_COMPARE_ATHLETE) { 
			// Athlete id will be returned
		}
	}

	
	private void returnAthleteSelectionByMode(long athleteId) {
		// Return the athlete
		if (mode == IntentExtras.ATHLETE_CHOICE_MODE_DISPLAY) {
			Log.i("PARKRUN", "Selected Athlete - Now launch the athlete display");
			Intent intent = new Intent(this, AthleteDisplay.class);
			startActivityForResult(intent, IntentExtras.ATHLETE_CHOICE_START_ATHLETE_DISPLAY);
		}
		else if (mode == IntentExtras.ATHLETE_CHOICE_MODE_SELECT) {
			Log.i("PARKRUN", "Selected Athlete - Return to success to caller.");
			// Return the athlete to the parent
			Intent intent = new Intent();
			intent.putExtra(IntentExtras.EXTRA_ATHLETE_CHOICE_SELECTED_ATHLETE, athleteId);
			setResult(RESULT_OK, intent);
			finish();
		}
	}
	
	
	public void addAthlete(View view) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Enter Athlete Number");
		alert.setMessage("Please enter the athlete number. This is found on your parkrun barcode. Enter the number after the 'A'.");

		// Set an EditText view to get user input
		final EditText input = new EditText(this);
		input.setKeyListener(DigitsKeyListener.getInstance());
		alert.setView(input);

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				Editable value = input.getText();
				addAthleteToList(value.toString());
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Cancelled.
			}
		});

		alert.setNeutralButton("Scan Barcode", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				scanBarcode();
			}
		});

		alert.show();
	}

	private void addAthleteToList(String athleteNumber) {
		Toast toast = Toast.makeText(getApplicationContext(), "Athlete to add: " + athleteNumber, AppSettings.WARNING_DISPLAY_TIME);
		toast.show();
		AthleteData entry = datasource.createAthlete(Long.parseLong(athleteNumber));
		adapter.add(entry);
		handleAthleteChoice(entry.getId());
	}

	/**
	 * Scan a barcode to get the athlete number.
	 * 
	 * @param view
	 */
	public void scanBarcode() {
		Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
		startActivityForResult(intent, IntentExtras.ATHLETE_CHOICE_SCAN_BARCODE);
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == IntentExtras.ATHLETE_CHOICE_SCAN_BARCODE) {
			if (resultCode == RESULT_OK) {
				String athleteNumber = splitAthleteNumber(intent.getStringExtra("SCAN_RESULT"));
				addAthleteToList(athleteNumber);
			} else if (resultCode == RESULT_CANCELED) {
				// Handle cancel
			}
		} else if (requestCode == IntentExtras.ATHLETE_CHOICE_START_ATHLETE_DISPLAY) {
			reloadListValues();
		}
	}

	public void deleteAthlete(final AthleteData athlete) {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Delete Athlete?");
		alert.setMessage("Do you want to delete the athlete: " + athlete.getName());

		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				AthleteDataSource datasource = new AthleteDataSource(getApplicationContext());
				datasource.open();
				datasource.deleteAthlete(athlete);
				datasource.close();
				reloadListValues();
			}
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				// Cancelled.
			}
		});

		alert.show();
	}

	private String splitAthleteNumber(String fullAthleteNumber) {
		if (fullAthleteNumber.startsWith("A")) {
			return fullAthleteNumber.substring(1);
		}
		return fullAthleteNumber;
	}

	private class AthleteListClickListener implements AdapterView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
			ListView athleteListView = (ListView) findViewById(R.id.athlete_id_list);
			AthleteData athlete = (AthleteData) athleteListView.getItemAtPosition(position);
			handleAthleteChoice(athlete.getId());
		}
	}

	private class AthleteListLongClickListener implements AdapterView.OnItemLongClickListener {
		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
			ListView athleteListView = (ListView) findViewById(R.id.athlete_id_list);
			AthleteData athlete = (AthleteData) athleteListView.getItemAtPosition(position);
			deleteAthlete(athlete);
			return true;
		}

	}
}
